import { Injectable } from '@nestjs/common';
import { CreateSysRoleDto } from './dto/create-sys-role.dto';
import { UpdateSysRoleDto } from './dto/update-sys-role.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { SysRole } from './entities/sys-role.entity';
import { Repository } from 'typeorm';
import { SysUser } from '../sys-user/entities/sys-user.entity';
import { SysMenuService } from '../sys-menu/sys-menu.service';
import * as _ from 'lodash';
@Injectable()
export class SysRoleService {
  constructor(
    @InjectRepository(SysRole)
    private readonly sysRoleRepository: Repository<SysRole>,
    private readonly sysMenuService: SysMenuService,
  ) {}

  // 获取角色列表
  async getRolePermission(user: any) {
    let roles = [];
    // 管理员拥有的权限
    if (SysUser.isAdmin(user.user_id)) {
      roles.push('admin');
    } else {
      const userRoles = user.roles;
      if (!userRoles || userRoles.length === 0) {
        return [];
      }
      roles = userRoles.map((item: any) => item.role_key);
    }
    return roles;
  }

  // 获取菜单权限集合
  async getMenuPermission(user: SysUser): Promise<any> {
    let perms = [];
    if (SysUser.isAdmin(user.user_id)) {
      perms.push('*:*:*');
    } else {
      const userRoles = user.roles;
      if (userRoles.length > 0) {
        for (let i = 0; i < userRoles.length; i++) {
          const role = userRoles[i];
          const rolePerms = await this.sysMenuService.selectMenuPermsByRoleId(
            role.role_id,
          );
          role['perms'] = rolePerms;
          perms = perms.concat(rolePerms);
        }
      } else {
        return [];
      }
    }
    return perms;
  }

  create(createSysRoleDto: CreateSysRoleDto) {
    return 'This action adds a new sysRole';
  }

  findAll() {
    return `This action returns all sysRole`;
  }

  findOne(id: number) {
    return `This action returns a #${id} sysRole`;
  }

  update(id: number, updateSysRoleDto: UpdateSysRoleDto) {
    return `This action updates a #${id} sysRole`;
  }

  remove(id: number) {
    return `This action removes a #${id} sysRole`;
  }
}
